const fs = require('fs');
const path = require('path');
const Database = require('better-sqlite3');
const { ensureDirSync } = require('../utils/pathUtils');
const config = require('../config');

let databaseInstance = null;

function readSqlFileSync(sqlFilePath) {
    return fs.readFileSync(sqlFilePath, { encoding: 'utf8' });
}

function runMigrations(db) {
    const migrationsDir = path.resolve(__dirname, 'migrations');
    const initSqlPath = path.join(migrationsDir, '001_init.sql');
    if (fs.existsSync(initSqlPath)) {
        const sql = readSqlFileSync(initSqlPath);
        db.exec(sql);
    }
}

function openDatabase() {
    if (databaseInstance) {
        return databaseInstance;
    }

    const databasePath = path.resolve(process.cwd(), config.DB_PATH || './data/downloads.db');
    const dataDir = path.dirname(databasePath);
    ensureDirSync(dataDir);

    const db = new Database(databasePath);
    db.pragma('journal_mode = WAL');
    db.pragma('synchronous = NORMAL');
    db.pragma('foreign_keys = ON');

    runMigrations(db);

    databaseInstance = db;
    return databaseInstance;
}

module.exports = {
    openDatabase,
};


